package com.mj.mybatis;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MyBatisHelper<E> {
    private SqlSessionFactory sf;
    private SqlSession ss;
    private Class e;
    public MyBatisHelper(){
        try {
            InputStream i = Resources.getResourceAsStream("mybatis-config.xml");
            this.sf = new SqlSessionFactoryBuilder().build(i);
            this.ss = this.sf.openSession();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public MyBatisHelper(Class e){
        try {
            InputStream i = Resources.getResourceAsStream("mybatis-config.xml");
            this.sf = new SqlSessionFactoryBuilder().build(i);
            this.ss = this.sf.openSession();
            this.e = e;
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
    public SqlSession getSession(){
        return this.ss;
    }
public E getMapper(){
        return (E)this.ss.getMapper(this.e);
}
public E getMapper(Class c){
return (E)this.ss.getMapper(c);
    }
   /* public void test(){
        System.out.println(e);
    }*/
    public void close(){
        if (this.ss!=null){
            this.ss.commit();
            this.ss.close();
        }
    }
}
